﻿using EagleProject.LinQDataContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EagleProject.Controllers
{
    public class PartnerController : MyController
    {
        //
        // GET: /Partner/
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Partner/ListSubscriber/{page}
        public ActionResult ListSubscriber(int? page)
        {
            int currentPageIndex = page.HasValue ? page.Value : 1;

            if (!IsAuthenticated()) return RedirectToLogin(@"~/Partner/ListSubscriber/" + currentPageIndex);
            if (!IsPartner()) return RedirectToAccessDenied();

            string uid = GetStringParam("uid");
            int stateId = GetIntParam("stateId");
            var data = GetData(currentPageIndex, NumberOfRecordPerPage, uid, stateId);

            if (Request.IsAjaxRequest())
                return PartialView("_AjaxSubscriberList", data);
            else
            {
                ViewBag.ListState = new SelectList(DatabaseController.GetStates(), "ID", "Name");
                return View(data);
            }
        }

        private MvcPaging.IPagedList<CommonSubscriberReg> GetData(
            int currentPageIndex, int numberPerPage, string uid, int stateId)
        {
            var listData = DatabaseController.GetAllCommonSubscriberReg();
            if (string.IsNullOrWhiteSpace(uid) && stateId <= 0) { }
            else
            {
                // Search by ID
                if (!string.IsNullOrWhiteSpace(uid))
                {
                    listData = from data in listData
                               where data.UniqueCode.Value.ToString().Equals(uid)
                               select data;
                }
                else
                {
                    listData = from data in listData
                               where data.LocalGovArea1.StateID == stateId
                               select data;
                }
            }

            var subData = MvcPaging.IQueryableExtensions.ToPagedList(listData, currentPageIndex, numberPerPage);

            return subData;
        }
    }
}
